<template>
    <div class="map-search">
        <Header />
        <div class="container">
            <div class="content-wrapper">
                <div class="map-container card">
                    <h2 class="section-title">地图找房</h2>
                    
                    <div class="map-layout">
                        <div id="map-container" class="main-map">
                            <!-- 地图加载状态 -->
                            <div v-if="!mapLoaded" class="map-loading">
                                <i class="el-icon-loading"></i>
                                <span>地图加载中...</span>
                            </div>
                            
                            <!-- 地图加载失败提示 -->
                            <div v-if="mapLoadError" class="map-error">
                                <div class="error-icon">
                                    <svg-icon name="common/warning" />
                                </div>
                                <div class="error-message">
                                    <h3>地图加载失败</h3>
                                    <p>您仍然可以在右侧查看附近的房源列表</p>
                                </div>
                            </div>
                            
                            <div class="map-controls">
                                <div class="control-group">
                                    <button class="control-btn" @click="getCurrentLocation" title="精确定位">
                                        <svg-icon name="map/location" />
                                    </button>
                                    <button class="control-btn" @click="zoomIn" title="放大">
                                        <svg-icon name="map/zoom-in" />
                                    </button>
                                    <button class="control-btn" @click="zoomOut" title="缩小">
                                        <svg-icon name="map/zoom-out" />
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="sidebar">
                            <div class="location-card">
                                <h3><svg-icon name="common/mappin" /> 当前定位</h3>
                                <p v-if="currentLocation">{{ currentLocation }}</p>
                                <p v-else class="text-muted">定位中...</p>
                            </div>
                            <div class="property-list">
                                <h3 class="list-title">附近房源（{{ properties.length }}）</h3>
                                <div class="list-container">
                                    <div v-for="property in properties" 
                                         :key="property.houseId || property.id" 
                                         class="property-card"
                                         @click="showPropertyDetails(property)">
                                        <div class="preview-image">
                                            <img 
                                              :src="getPropertyImage(property)" 
                                              :data-original-src="property.imageUrl || property.coverImage"
                                              @error="onImageError"
                                              alt="房源预览">
                                        </div>
                                        <div class="info">
                                            <h4>{{ property.title || '未命名房源' }}</h4>
                                            <p class="price">¥{{ formatPrice(property.price || 0) }}<span>万元</span></p>
                                            <div class="meta">
                                                <span><svg-icon name="house/info/area" /> {{ property.area || 0 }}㎡</span>
                                                <span><svg-icon name="house/info/bedroom" /> {{ property.layout || '暂无户型' }}</span>
                                            </div>
                                            <button class="collect-btn" @click.stop="handleCollect(property.houseId || property.id)">
                                                <svg-icon name="house/info/star-filled" />
                                                收藏
                                            </button>
                                        </div>
                                    </div>
                                    <div v-if="properties.length === 0" class="empty-list">
                                        <svg-icon name="common/empty" />
                                        <p>暂无房源数据</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>
        <Footer />
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import Header from '@/views/common/Header.vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import request from '@/utils/request'
import { getFullImageUrl, getHouseImageUrl } from '@/utils/imageUrl'
import { collectHouse, getHouseImages, getHouseDetail } from '@/api/house'
import Footer from '@/views/common/Footer.vue'

// 配置 - 是否使用模拟数据 - 设置为false使用真实数据
const useMockData = ref(false)
// 配置 - 每次随机生成的房源数量 (仅在useMockData=true时使用)
const MOCK_HOUSE_COUNT = 8

const map = ref(null)
const properties = ref([]) // 房源数据
const currentLocation = ref(null)
const mapLoaded = ref(false)
const mapLoadError = ref(false) // 新增地图加载失败标志
const markers = ref([]) // 存储多个标记点
const geocoder = ref(null)

// 初始化地图
const initMap = async () => {
    try {
        console.log('开始加载地图...')
        // 在加载 SDK 之前配置安全码
        window._AMapSecurityConfig = {
            securityJsCode: 'dd5f8229f90062eef530f238093f0f0e'
        }
        
        // 添加全局错误处理，避免地图错误影响整个应用
        const originalOnError = window.onerror;
        window.onerror = function(message, source, lineno, colno, error) {
            // 过滤高德地图相关错误
            if (source && (source.includes('amap') || source.includes('AMap') || source.includes('maps?callback'))) {
                console.warn('高德地图错误(已处理):', message, error);
                // 不传播错误
                return true;
            }
            
            // 调用原始的错误处理程序
            if (typeof originalOnError === 'function') {
                return originalOnError.apply(this, arguments);
            }
            return false;
        };

        try {
            // 加载高德地图SDK，确保包含需要的插件
            const AMap = await AMapLoader.load({
                key: '20043a52000d4a5ba4ac9d73c3f097d0',
                version: '2.0',
                plugins: ['AMap.Geolocation', 'AMap.Geocoder', 'AMap.CitySearch', 'AMap.ToolBar', 'AMap.Scale']
            })

            console.log('SDK加载成功')

            // 获取用户IP定位
            const defaultCenter = await getIpLocation(AMap)
            
            // 创建地图实例
            map.value = new AMap.Map('map-container', {
                zoom: 15,
                center: defaultCenter,
                resizeEnable: true,
                viewMode: '2D'
            })

            // 添加控件
            map.value.addControl(new AMap.ToolBar())
            map.value.addControl(new AMap.Scale())

            // 初始化地理编码服务
            geocoder.value = new AMap.Geocoder({
                city: "全国"
            })
            
            // 等待地图加载完成
            map.value.on('complete', () => {
                console.log('地图渲染完成')
                mapLoaded.value = true
                mapLoadError.value = false
                
                // 获取初始位置的房源
                fetchProperties(defaultCenter)
            })
            
            // 添加超时处理
            setTimeout(() => {
                if (!mapLoaded.value) {
                    console.warn('地图加载超时，强制设置为已加载')
                    mapLoaded.value = true
                    mapLoadError.value = false
                    
                    // 获取初始位置的房源
                    fetchProperties(defaultCenter)
                }
            }, 5000)
        } catch (sdkError) {
            console.error('加载高德地图SDK失败:', sdkError)
            ElMessage.error('地图加载失败，请刷新重试')
            
            // 设置加载失败标志
            mapLoaded.value = true
            mapLoadError.value = true
            
            // 如果SDK加载失败，尝试使用模拟数据展示UI
            console.log('尝试使用模拟数据...')
            useMockData.value = true
            fetchProperties([116.397455, 39.909187]) // 默认北京
        }
    } catch (error) {
        console.error('地图初始化失败:', error)
        ElMessage.error('地图加载失败，请刷新重试')
        mapLoaded.value = true
        mapLoadError.value = true
        
        // 失败后也尝试加载房源数据
        useMockData.value = true
        fetchProperties([116.397455, 39.909187]) // 默认北京
    }
}

// 通过IP获取位置
const getIpLocation = (AMap) => {
    return new Promise((resolve) => {
        const citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(async (status, result) => {
            if (status === 'complete' && result.city) {
                // 获取城市中心点
                const geocoder = new AMap.Geocoder()
                geocoder.getLocation(result.city, (geoStatus, geoResult) => {
                    if (geoStatus === 'complete' && geoResult.geocodes.length) {
                        const location = geoResult.geocodes[0].location
                        currentLocation.value = result.city
                        resolve([location.lng, location.lat])
                    } else {
                        resolve([116.397455, 39.909187]) // 默认北京
                    }
                })
            } else {
                resolve([116.397455, 39.909187]) // 默认北京
            }
        })
    })
}

// 使用高德地图定位
const useAMapGeolocation = () => {
    if (!map.value) {
        ElMessage.error('地图尚未加载完成，请稍后再试')
        return
    }
    
    try {
        // 创建定位对象
        const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            convert: true, // 自动偏移坐标
            showButton: false,
            showMarker: true,
            showCircle: true,
            panToLocation: true,
            zoomToAccuracy: true
        })
        
        ElMessage.info('正在获取位置...')
        
        geolocation.getCurrentPosition((status, result) => {
            if (status === 'complete') {
                const { position, formattedAddress } = result
                currentLocation.value = formattedAddress
                map.value.setCenter(position)
                ElMessage.success('定位成功')
                fetchProperties(position)
            } else {
                ElMessage.error('定位失败，请检查位置权限')
                // 使用默认位置
                map.value.setCenter([116.397455, 39.909187])
                fetchProperties([116.397455, 39.909187])
            }
        })
    } catch (error) {
        console.error('定位失败:', error)
        ElMessage.error('定位服务初始化失败，请刷新页面重试')
    }
}

// 清除所有标记点
const clearMarkers = () => {
    if (markers.value.length > 0) {
        markers.value.forEach(marker => {
            map.value.remove(marker)
        })
        markers.value = []
    }
}

// 根据位置获取房源
const fetchProperties = async (position) => {
    try {
        const [lng, lat] = position
        ElMessage.info('正在获取附近房源...')
        console.log('开始获取附近房源 - 当前位置:', { lng, lat })
        
        let data = null
        
        if (!useMockData.value) {
            // 使用真实API
            try {
                console.log('请求附近房源 - GET /house/nearby:', { lng, lat, radius: 10000 })
                const response = await request({
                    url: '/house/nearby',
                    method: 'get',
                    params: {
                        lng,
                        lat,
                        radius: 10000,
                        pageNum: 1,
                        pageSize: 50 // 增加获取的房源数量
                    }
                })
                data = response
                console.log('附近房源API返回数据:', data)
                
                // 如果后端返回数据正常但records为空，自动切换到模拟数据
                if (data.code === 200 && (!data.data || !data.data.records || data.data.records.length === 0)) {
                    console.log('后端返回空数据，自动切换到模拟数据进行测试')
                    ElMessage.warning('未找到附近房源，已自动切换到模拟数据进行测试')
                    useMockData.value = true
                    data = generateMockData(lng, lat, MOCK_HOUSE_COUNT)
                } else if (data.code === 200 && data.data.records) {
                    // 处理房源图片和详情
                    const houseList = data.data.records;
                    for (const house of houseList) {
                        if (house.houseId) {
                            try {
                                // 尝试从详情API获取图片
                                const detailResponse = await getHouseDetail(house.houseId);
                                if (detailResponse.code === 200 && detailResponse.data) {
                                    const detailData = detailResponse.data;
                                    
                                    // 提取关键数据
                                    console.log(`房源${house.houseId}详情API返回数据:`, detailData);
                                    
                                    // 提取更详细的房源信息
                                    Object.assign(house, {
                                        // 仅更新缺失的字段，保留原有数据
                                        title: house.title || detailData.title || `房源${house.houseId}`,
                                        description: house.description || detailData.description,
                                        bedroom: house.bedroom || detailData.bedroom,
                                        bathroom: house.bathroom || detailData.bathroom,
                                        livingRoom: house.livingRoom || detailData.livingRoom || detailData.living_room,
                                        // 重要: 面积和价格
                                        area: house.area || detailData.area,
                                        price: house.price || detailData.price
                                    });
                                    
                                    // 价格和面积特殊处理
                                    if (detailData.price !== undefined && detailData.price !== null && !house.price) {
                                        console.log(`使用详情API获取到价格:`, detailData.price);
                                        const priceUnit = detailData.priceUnit || '元';
                                        const numPrice = parseFloat(detailData.price);
                                        if (!isNaN(numPrice)) {
                                            // 根据单位处理
                                            if (priceUnit === '万' || priceUnit === '万元') {
                                                house.price = numPrice;
                                            } else {
                                                // 默认单位为元，转换为万元
                                                house.price = numPrice / 10000;
                                            }
                                        }
                                    }
                                    
                                    if (detailData.area !== undefined && detailData.area !== null && !house.area) {
                                        console.log(`使用详情API获取到面积:`, detailData.area);
                                        house.area = parseFloat(detailData.area) || 0;
                                    }
                                    
                                    // 提取图片信息
                                    if (detailData.images && detailData.images.length > 0) {
                                        // 确保images是字符串数组而不是对象数组
                                        house.images = detailData.images.map(img => 
                                            typeof img === 'string' ? img : (img.imageUrl || img.url || img.image_url || img.src || '')
                                        ).filter(url => url); // 过滤掉空字符串
                                        
                                        if (!house.coverImage && house.images.length > 0) {
                                            house.coverImage = house.images[0];
                                        }
                                        console.log(`房源ID:${house.houseId} 获取到${house.images.length}张图片`);
                                    } else if (detailData.imageList && detailData.imageList.length > 0) {
                                        // 同样处理imageList
                                        house.images = detailData.imageList.map(img => 
                                            typeof img === 'string' ? img : (img.imageUrl || img.url || img.image_url || img.src || '')
                                        ).filter(url => url);
                                        
                                        if (!house.coverImage && house.images.length > 0) {
                                            house.coverImage = house.images[0];
                                        }
                                        console.log(`房源ID:${house.houseId} 获取到${house.images.length}张图片`);
                                    } else if (detailData.coverImage) {
                                        house.coverImage = detailData.coverImage;
                                        console.log(`房源ID:${house.houseId} 获取到封面图片`);
                                    }
                                }
                            } catch (error) {
                                console.warn(`获取房源详情失败，房源ID: ${house.houseId}`, error);
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('API请求失败:', error)
                ElMessage.error('获取房源API请求失败，已自动切换到模拟数据')
                useMockData.value = true
                data = generateMockData(lng, lat, MOCK_HOUSE_COUNT)
            }
        } else {
            // 使用模拟数据
            data = generateMockData(lng, lat, MOCK_HOUSE_COUNT)
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 800))
            console.log('使用模拟数据:', data)
        }
        
        if (data.code === 200 && data.data) {
            // 处理分页数据结构
            const houseList = data.data.records || []
            console.log('获取到房源列表:', houseList.length, '条记录')
            
            if (houseList.length === 0) {
                ElMessage.info('附近暂无房源，可以尝试：\n1. 放大搜索范围\n2. 移动到其他区域')
                return
            }
            
            // 处理每个房源的数据
            const processedHouses = houseList.map(house => {
                // 确保经纬度是数字类型，尝试从更多可能的字段获取经纬度
                const lng = parseFloat(house.lng || house.longitude || house.lngBaidu || house.longitudeBaidu || house.x || 0);
                const lat = parseFloat(house.lat || house.latitude || house.latBaidu || house.latitudeBaidu || house.y || 0);
                
                console.log(`处理房源数据，ID:${house.houseId}，原始数据:`, house);
                
                // 确保基本字段存在
                house.title = house.title || house.name || `未命名房源-${house.houseId}`;
                
                // 处理价格，确保有适当的格式（从元转换为万元）
                const priceUnit = house.priceUnit || house.price_unit || '元';
                let price = 0;
                
                // 打印原始价格数据
                console.log(`房源ID:${house.houseId} 原始价格数据:`, {
                    price: house.price,
                    priceUnit: priceUnit,
                    type: typeof house.price
                });
                
                if (house.price !== undefined && house.price !== null) {
                    // 确保价格是数字
                    const numPrice = parseFloat(house.price);
                    if (!isNaN(numPrice)) {
                        // 根据单位处理
                        if (priceUnit === '万' || priceUnit === '万元') {
                            price = numPrice;
                        } else if (priceUnit === '10000') {
                            // 对于某些价格单位为10000的情况
                            price = numPrice / 10000;
                        } else {
                            // 默认单位为元，转换为万元
                            price = numPrice / 10000;
                        }
                    }
                }
                
                // 打印处理后的价格
                console.log(`房源ID:${house.houseId} 处理后价格: ${price}万元`);
                
                // 构建户型字符串
                const bedroom = parseInt(house.bedroom) || 0;
                const livingRoom = parseInt(house.livingRoom || house.living_room) || 0;
                const bathroom = parseInt(house.bathroom) || 0;
                const layout = house.layout || `${bedroom}室${livingRoom}厅${bathroom}卫`;
                
                // 处理小区名称
                const addressParts = (house.address || '').split(' ');
                const community = house.community || house.communityName || (addressParts.length > 0 ? addressParts[0] : '未知小区');
                
                // 处理面积
                let area = 0;
                if (house.area !== undefined && house.area !== null) {
                    area = parseFloat(house.area);
                    if (isNaN(area)) area = 0;
                }
                
                // 打印处理后的面积
                console.log(`房源ID:${house.houseId} 处理后面积: ${area}㎡`);
                
                // 处理图片
                const coverImage = house.coverImage || (house.images && house.images.length > 0 ? house.images[0] : '/images/house/default-house.jpg');
                
                // 创建处理后的房源对象
                const processedHouse = {
                    ...house,
                    // 确保houseId存在
                    houseId: house.houseId || house.id,
                    // 保存经纬度
                    longitude: lng,
                    latitude: lat,
                    // 处理图片URL - 使用数据库中的封面图片
                    coverImage: coverImage,
                    // 处理价格 - 确保是数字
                    price: price,
                    // 处理户型
                    layout: layout,
                    // 添加房源分组标识（用于右侧列表分组）
                    district: house.district || '未知区域',
                    community: community,
                    // 处理面积 - 确保是数字
                    area: area,
                    // 处理地址
                    address: house.address || `${house.province || ''}${house.city || ''}${house.district || ''}`
                };
                
                return processedHouse;
            });
            
            // 先保存所有处理后的房源数据到列表
            properties.value = processedHouses
            ElMessage.success(`找到 ${processedHouses.length} 个房源`)
            
            // 如果地图不可用，直接返回
            if (!map.value || !mapLoaded.value) {
                console.log('地图未加载完成，仅显示房源列表');
                return;
            }
            
            // 尝试对没有经纬度的房源进行地理编码
            if (processedHouses.length > 0 && geocoder.value) {
                const housesWithoutCoords = processedHouses.filter(house => 
                    (!house.longitude || !house.latitude || 
                     Math.abs(house.longitude) < 0.000001 && Math.abs(house.latitude) < 0.000001) && 
                    house.address
                );
                
                if (housesWithoutCoords.length > 0) {
                    console.log(`尝试对${housesWithoutCoords.length}个房源进行地理编码`);
                    
                    // 使用Promise.all进行批量地理编码
                    await Promise.all(housesWithoutCoords.map(house => {
                        return new Promise(resolve => {
                            geocoder.value.getLocation(house.address, (status, result) => {
                                if (status === 'complete' && result.geocodes.length > 0) {
                                    const location = result.geocodes[0].location;
                                    house.longitude = location.lng;
                                    house.latitude = location.lat;
                                    console.log(`通过地址获取经纬度成功，房源ID:${house.houseId}, 地址:${house.address}, 经纬度:[${location.lng}, ${location.lat}]`);
                                } else {
                                    console.warn(`地理编码失败，房源ID:${house.houseId}, 地址:${house.address}`);
                                }
                                resolve();
                            });
                        });
                    }));
                }
            }
            
            // 过滤掉没有有效经纬度的房源
            const validHouses = processedHouses.filter(house => {
                const hasValidCoords = 
                    house.longitude && house.latitude && 
                    !isNaN(house.longitude) && !isNaN(house.latitude) &&
                    (Math.abs(house.longitude) > 0.000001 || Math.abs(house.latitude) > 0.000001);
                
                if (!hasValidCoords) {
                    console.log(`房源ID:${house.houseId} 经纬度无效: [${house.longitude}, ${house.latitude}]`);
                }
                
                return hasValidCoords;
            });
            
            console.log('有效的房源数量(有经纬度):', validHouses.length);
            
            if (validHouses.length === 0) {
                console.warn('所有房源都缺少有效经纬度:');
                ElMessage.warning('找到的房源没有有效的位置信息，无法在地图上显示')
                return
            }
            
            // 清除旧的标记
            clearMarkers()
            
            try {
                // 按小区分组房源，以便创建聚合标记
                const communitiesMap = {}
                validHouses.forEach(house => {
                    const key = `${house.community}_${house.longitude.toFixed(6)}_${house.latitude.toFixed(6)}`
                    if (!communitiesMap[key]) {
                        communitiesMap[key] = {
                            name: house.community,
                            longitude: house.longitude,
                            latitude: house.latitude,
                            houses: []
                        }
                    }
                    communitiesMap[key].houses.push(house)
                })
                
                console.log('按小区分组后:', Object.keys(communitiesMap).length, '个小区');
                
                // 在地图上添加小区标记
                Object.values(communitiesMap).forEach(community => {
                    try {
                        const { name, longitude, latitude, houses } = community
                        
                        // 创建小区标记
                        const marker = new AMap.Marker({
                            position: [longitude, latitude],
                            map: map.value,
                            // 添加自定义样式
                            content: `<div class="community-marker">
                                <span class="count">${houses.length}</span>
                            </div>`,
                            // 存储小区数据
                            extData: { community, houses }
                        })
                        
                        // 创建信息窗体
                        const infoWindow = new AMap.InfoWindow({
                            content: `
                                <div style="padding: 10px; min-width: 200px;">
                                    <h4 style="margin: 0 0 5px; color: #4A60A1;">${name}</h4>
                                    <p style="margin: 5px 0; font-size: 14px; color: #333;">
                                        共有 <span style="color: #f56c6c; font-weight: bold;">${houses.length}</span> 套房源
                                    </p>
                                    <p style="margin: 5px 0 0; font-size: 12px; color: #666;">
                                        价格：${formatPrice(Math.min(...houses.map(h => h.price)))} - 
                                        ${formatPrice(Math.max(...houses.map(h => h.price)))}万元
                                    </p>
                                    <button onclick="window.viewCommunityHouses('${name}')"
                                        style="margin-top: 10px; background: #4A60A1; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; width: 100%;">
                                        查看全部房源
                                    </button>
                                </div>
                            `,
                            offset: new AMap.Pixel(0, -30)
                        })
                        
                        // 添加点击事件
                        marker.on('click', () => {
                            // 关闭其他信息窗体
                            markers.value.forEach(m => {
                                if (m.infoWindow) m.infoWindow.close()
                            })
                            
                            // 打开当前信息窗体
                            infoWindow.open(map.value, marker.getPosition())
                            
                            // 更新右侧列表显示该小区的房源
                            updatePropertyList(houses)
                        })
                        
                        // 保存信息窗体引用
                        marker.infoWindow = infoWindow
                        
                        map.value.add(marker)
                        markers.value.push(marker)
                    } catch (err) {
                        console.error('创建小区标记失败:', err)
                    }
                })
                
                // 调整地图视野以包含所有标记
                if (markers.value.length > 0) {
                    map.value.setFitView(markers.value, {
                        padding: [60, 60, 60, 60]
                    })
                    console.log(`成功创建了 ${markers.value.length} 个地图标记`);
                } else {
                    console.error('没有创建任何标记点');
                }
            } catch (mapError) {
                console.error('在地图上添加标记时发生错误:', mapError);
                ElMessage.error('在地图上显示房源位置时出错');
            }
        } else {
            console.error('API响应异常:', data);
            ElMessage.error(data?.msg || '获取房源失败')
        }
    } catch (error) {
        console.error('获取附近房源失败:', error)
        ElMessage.error('获取房源信息失败，请刷新重试')
    }
}

// 更新右侧列表显示
const updatePropertyList = (propertyList) => {
    properties.value = propertyList || []
}

// 格式化价格显示
const formatPrice = (price) => {
    // 打印原始价格参数
    console.log('formatPrice接收到参数:', price, typeof price);
    
    // 处理无效值
    if (price === undefined || price === null || isNaN(price)) {
        return '0';
    }
    
    // 确保转换为数字类型
    const numPrice = parseFloat(price);
    
    // 处理0或NaN
    if (!numPrice) return '0';
    
    // 保留整数，如果是整数则直接显示，否则保留2位小数
    const formattedPrice = Number.isInteger(numPrice) ? numPrice.toString() : numPrice.toFixed(2);
    
    // 打印格式化后的结果
    console.log('价格格式化结果:', formattedPrice);
    
    return formattedPrice;
}

// 生成模拟数据
const generateMockData = (baseLng, baseLat, count = 5) => {
    const houseTypes = ['1室1厅', '2室1厅', '2室2厅', '3室1厅', '3室2厅', '4室2厅']
    const addresses = ['阳光花园', '城市中心', '湖景花园', '青年公寓', '江景豪庭', '中央广场', '商业大厦', '东湖小区', '星光家园']
    const titles = [
        '精装修小户型', '南北通透两居室', '阳光充足三居室', '豪华装修四居室', 
        '低楼层靠近地铁', '高楼层视野好', '精装修拎包入住', '全新装修首次出售',
        '交通便利地段好', '大学旁安静舒适', '地铁口学区房', '带花园大露台'
    ]
    
    const mockHouses = []
    
    for (let i = 0; i < count; i++) {
        // 随机生成距离主点1-5公里的坐标
        const distance = Math.random() * 4000 + 1000 // 1000-5000米
        const direction = Math.random() * Math.PI * 2 // 随机方向
        
        // 计算经纬度偏移
        // 经度: 1度约111公里(赤道处),纬度:1度约111公里
        // 简化计算，使用常数111000作为度到米的转换
        const latOffset = (Math.sin(direction) * distance) / 111000
        const lngOffset = (Math.cos(direction) * distance) / (111000 * Math.cos(baseLat * Math.PI / 180))
        
        const layout = houseTypes[Math.floor(Math.random() * houseTypes.length)]
        const address = addresses[Math.floor(Math.random() * addresses.length)]
        const title = `${address}${layout} ${titles[Math.floor(Math.random() * titles.length)]}`
        
        // 随机房屋面积
        let area
        if (layout.startsWith('1')) area = Math.floor(Math.random() * 20) + 35 // 35-55
        else if (layout.startsWith('2')) area = Math.floor(Math.random() * 30) + 60 // 60-90
        else if (layout.startsWith('3')) area = Math.floor(Math.random() * 40) + 90 // 90-130
        else area = Math.floor(Math.random() * 50) + 130 // 130-180
        
        // 根据面积和随机因素计算售房价格（万元）
        // 每平米1-3万元不等
        const unitPrice = Math.floor(Math.random() * 2) + 1
        const price = Math.floor(area * unitPrice / 5) * 5 // 按面积*单价计算，然后取整到5的倍数
        
        mockHouses.push({
            houseId: 1000 + i,
            title,
            price,
            area,
            layout,
            longitude: Number(baseLng) + lngOffset,
            latitude: Number(baseLat) + latOffset,
            address: `${address}小区`,
            imageUrl: `https://picsum.photos/id/${Math.floor(Math.random() * 1000)}/300/200`,
            distance
        })
    }
    
    // 按距离排序
    mockHouses.sort((a, b) => a.distance - b.distance)
    
    return {
        code: 200,
        msg: "操作成功",
        data: {
            records: mockHouses,
            total: mockHouses.length,
            size: count,
            current: 1
        }
    }
}

// 显示房源详情
const showPropertyDetails = (property) => {
    // 跳转到房源详情页面
    console.log('查看房源:', property);
    
    try {
        const houseId = property.houseId;
        if (houseId) {
            // 使用完整URL路径以确保正确跳转
            const baseUrl = window.location.origin;
            const url = `${baseUrl}/house/${houseId}`;
            console.log(`跳转到房源详情页: ${url}`);
            
            // 记录更多信息以便调试
            console.log(`房源详情: ID=${houseId}, 标题=${property.title}, 地址=${property.address}`);
            
            // 先在新标签页中打开，以保留当前地图状态
            window.open(url, '_blank');
        } else {
            console.error('无效的房源ID:', property);
            ElMessage.warning('无效的房源ID，无法查看详情');
        }
    } catch (error) {
        console.error('房源详情跳转失败:', error);
        ElMessage.error('跳转失败，请稍后重试');
    }
    
    // 如果地图加载成功，突出显示该房源的标记
    if (map.value && markers.value.length > 0) {
        // 查找对应的标记
        const matchingMarkers = markers.value.filter(marker => {
            const extData = marker.getExtData();
            if (extData && extData.houses) {
                // 检查这个小区标记是否包含当前房源
                return extData.houses.some(h => h.houseId === property.houseId);
            }
            return false;
        });
        
        if (matchingMarkers.length > 0) {
            const marker = matchingMarkers[0];
            // 设置地图中心点
            map.value.setCenter(marker.getPosition());
            
            // 打开信息窗体
            if (marker.infoWindow) {
                marker.infoWindow.open(map.value, marker.getPosition());
            }
            
            // 设置标记样式
            marker.setContent(`<div class="community-marker active">
                <span class="count">${marker.getExtData().houses.length}</span>
            </div>`);
            
            // 恢复其他标记的样式
            markers.value.forEach(m => {
                if (m !== marker) {
                    const extData = m.getExtData();
                    m.setContent(`<div class="community-marker">
                        <span class="count">${extData.houses.length}</span>
                    </div>`);
                    
                    // 关闭其他信息窗体
                    if (m.infoWindow) {
                        m.infoWindow.close();
                    }
                }
            });
        }
    }
}

// 地图控件功能
const zoomIn = () => {
    if (!map.value) return
    const zoom = map.value.getZoom()
    map.value.setZoom(zoom + 1)
}

const zoomOut = () => {
    if (!map.value) return
    const zoom = map.value.getZoom()
    map.value.setZoom(zoom - 1)
}

// 获取精确位置
const getCurrentLocation = async () => {
    ElMessage.info('正在获取精确位置...')
    
    try {
        // 优先使用浏览器定位API
        if (navigator.geolocation) {
            const position = await new Promise((resolve, reject) => {
                navigator.geolocation.getCurrentPosition(resolve, reject, {
                    enableHighAccuracy: true,
                    timeout: 5000,
                    maximumAge: 0
                })
            })
            
            const { latitude, longitude } = position.coords
            const location = [longitude, latitude]
            
            // 更新地图中心点
            map.value.setCenter(location)
            map.value.setZoom(16) // 设置更大的缩放级别以获得更详细的视图
            
            // 清除旧标记
            clearMarkers()
            
            // 获取详细地址
            if (geocoder.value) {
                geocoder.value.getAddress(location, (status, result) => {
                    if (status === 'complete') {
                        currentLocation.value = result.regeocode.formattedAddress
                        ElMessage.success('定位成功')
                    }
                })
            }
            
            // 获取附近房源
            await fetchProperties(location)
            
        } else {
            throw new Error('浏览器不支持地理定位')
        }
    } catch (error) {
        console.error('精确定位失败:', error)
        ElMessage.error('无法获取精确位置，将使用IP定位')
        useAMapGeolocation()
    }
}

// 注册全局函数以供信息窗体使用
const setupGlobalFunctions = () => {
    // 房源详情页跳转
    window.viewHouseDetail = (houseId) => {
        if (!houseId) return
        // 使用完整URL路径以确保正确跳转
        const baseUrl = window.location.origin;
        window.location.href = `${baseUrl}/house/${houseId}`;
        console.log(`跳转到房源详情页: ${baseUrl}/house/${houseId}`);
    }
    
    // 收藏/取消收藏
    window.toggleCollect = async (houseId) => {
        if (!houseId) return
        
        try {
            const res = await collectHouse(houseId)
            if (res.code === 200) {
                ElMessage.success('收藏成功')
            } else {
                ElMessage.error(res.msg || '操作失败')
            }
        } catch (error) {
            console.error('收藏/取消收藏失败:', error)
            ElMessage.error('操作失败，请稍后重试')
        }
    }
    
    // 查看小区全部房源
    window.viewCommunityHouses = (communityName) => {
        if (!communityName) return
        
        // 找到小区对应的标记
        const communityMarker = markers.value.find(marker => {
            const data = marker.getExtData()
            return data && data.community && data.community.name === communityName
        })
        
        if (communityMarker) {
            const data = communityMarker.getExtData()
            
            // 更新右侧列表
            updatePropertyList(data.houses)
            
            // 设置小区标记为活跃状态
            markers.value.forEach(marker => {
                const extData = marker.getExtData()
                if (extData && extData.community) {
                    if (extData.community.name === communityName) {
                        marker.setContent(`<div class="community-marker active">
                            <span class="count">${extData.houses.length}</span>
                        </div>`)
                    } else {
                        marker.setContent(`<div class="community-marker">
                            <span class="count">${extData.houses.length}</span>
                        </div>`)
                    }
                }
            })
        }
    }
}

// 处理每个房源的图片URL
const getPropertyImage = (property) => {
    // 记录原始属性以便调试
    console.log(`处理房源图片，ID:${property.houseId}，图片相关属性:`, {
        coverImage: property.coverImage,
        imageUrl: property.imageUrl,
        images: property.images,
        hasImages: property.images && property.images.length > 0
    });
    
    // 尝试从多个字段获取房源图片
    let imageSource = null;
    
    // 1. 优先使用coverImage
    if (property.coverImage) {
        imageSource = property.coverImage;
        console.log(`使用coverImage: ${imageSource}`);
    } 
    // 2. 其次使用images数组第一张
    else if (property.images && property.images.length > 0) {
        imageSource = property.images[0];
        console.log(`使用images[0]: ${imageSource}`);
    } 
    // 3. 再次使用imageUrl
    else if (property.imageUrl) {
        imageSource = property.imageUrl;
        console.log(`使用imageUrl: ${imageSource}`);
    }
    // 4. 最后使用其他可能的字段
    else if (property.cover_image || property.main_image || property.mainImage) {
        imageSource = property.cover_image || property.main_image || property.mainImage;
        console.log(`使用其他图片字段: ${imageSource}`);
    }
    
    // 调试日志，检查imageSource的类型和值
    console.log(`最终选择的图片源，类型:${typeof imageSource}，值:`, imageSource);
    
    if (!imageSource) {
        console.log(`房源ID:${property.houseId} 没有图片，使用默认图片`);
        return '/images/house/default-house.jpg';
    }
    
    // 处理imageSource是对象而不是字符串的情况
    if (typeof imageSource === 'object') {
        // 如果是对象，尝试提取imageUrl字段
        if (imageSource.imageUrl) {
            console.log(`图片是对象，使用imageUrl:`, imageSource.imageUrl);
            // 如果已经是绝对路径，直接返回
            if (imageSource.imageUrl.startsWith('http') || imageSource.imageUrl.startsWith('/')) {
                return imageSource.imageUrl;
            }
            return getHouseImageUrl(imageSource.imageUrl);
        } else if (imageSource.url) {
            console.log(`图片是对象，使用url:`, imageSource.url);
            // 如果已经是绝对路径，直接返回
            if (imageSource.url.startsWith('http') || imageSource.url.startsWith('/')) {
                return imageSource.url;
            }
            return getHouseImageUrl(imageSource.url);
        } else {
            console.log(`图片是对象但没有URL字段，使用默认图片`);
            return '/images/house/default-house.jpg';
        }
    }
    
    // 如果是字符串且是绝对路径或默认图片，直接返回
    if (typeof imageSource === 'string') {
        if (imageSource.startsWith('http') || 
            imageSource.startsWith('https') || 
            imageSource.startsWith('/images/') || 
            imageSource.startsWith('/assets/')) {
            console.log(`图片是绝对路径，直接返回:`, imageSource);
            return imageSource;
        }
    }
    
    // 如果是相对路径字符串，通过工具函数处理
    try {
        const imageUrl = getHouseImageUrl(imageSource);
        console.log(`通过getHouseImageUrl处理后:`, imageUrl);
        return imageUrl;
    } catch (error) {
        console.error(`房源ID:${property.houseId} 处理图片URL失败:`, error);
        return '/images/house/default-house.jpg';
    }
}

// 图片加载错误处理
const onImageError = (e) => {
    const originalSrc = e.target.getAttribute('data-original-src') || e.target.src;
    
    // 保存原始路径用于调试
    e.target.setAttribute('data-original-src', originalSrc);
    console.log('图片加载失败:', originalSrc);
    
    // 设置默认图片 - 确保使用绝对路径
    const defaultImage = '/images/house/default-house.jpg';
    
    // 避免设置相同的图片URL导致循环触发error事件
    if (e.target.src !== defaultImage && !e.target.src.endsWith(defaultImage)) {
        e.target.src = defaultImage;
    }
    
    // 防止循环触发error事件
    e.target.onerror = null;
}

// 处理收藏按钮点击
const handleCollect = async (houseId) => {
    if (!houseId) {
        ElMessage.warning('无效的房源ID')
        return
    }
    
    try {
        const res = await collectHouse(houseId)
        if (res.code === 200) {
            ElMessage.success('收藏成功')
        } else {
            ElMessage.error(res.msg || '操作失败')
        }
    } catch (error) {
        console.error('收藏房源失败:', error)
        ElMessage.error('操作失败，请稍后重试')
    }
}

// 页面挂载时初始化
onMounted(() => {
    // 设置全局函数
    setupGlobalFunctions()
    
    // 初始化地图
    initMap()
})

// 页面卸载
onUnmounted(() => {
    // 清除全局函数
    window.viewHouseDetail = null
    window.toggleCollect = null
    
    if (map.value) {
        map.value.destroy()
    }
})
</script>

<style lang="scss" scoped>
// 为地图中的canvas元素添加willReadFrequently属性
:deep(canvas) {
    will-change: contents;
}

.map-search {
    .map-container {
        margin-top: 127px;
        padding: 24px;
        background: #fff;
        border-radius: 12px;

        .section-title {
            font-size: 24px;
            color: #2F3B59;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid #eee;
            font-weight: 600;
        }
    }

    .map-layout {
        display: grid;
        grid-template-columns: 1fr 380px;
        gap: 24px;
        height: 880px;
    }

    .main-map {
        position: relative;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        
        // 地图加载状态
        .map-loading {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.8);
            z-index: 999;
            
            i {
                font-size: 32px;
                color: #4A60A1;
                margin-bottom: 12px;
            }
            
            span {
                color: #666;
                font-size: 16px;
            }
        }
        
        // 地图加载失败提示
        .map-error {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.9);
            z-index: 999;
            
            .error-icon {
                width: 64px;
                height: 64px;
                margin-bottom: 12px;
                
                svg {
                    width: 100%;
                    height: 100%;
                    color: #f56c6c;
                }
            }
            
            .error-message {
                text-align: center;
                
                h3 {
                    font-size: 18px;
                    color: #f56c6c;
                    margin-bottom: 8px;
                }
                
                p {
                    font-size: 14px;
                    color: #666;
                }
            }
        }
    }

    .sidebar {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .location-card {
        background: #f8f9fa;
        padding: 16px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        
        h3 {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
            color: #4A60A1;
            margin-bottom: 12px;
            
            .svg-icon {
                width: 18px;
                height: 18px;
            }
        }
        
        p {
            margin: 0;
            font-size: 14px;
            color: #666;
            
            &.text-muted {
                color: #999;
                font-style: italic;
            }
        }
    }

    .property-list {
        flex: 1;
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

        .list-title {
            padding: 16px;
            margin: 0;
            font-size: 16px;
            background: #f8f9fa;
            color: #4A60A1;
            font-weight: 600;
            border-bottom: 1px solid #eee;
        }

        .list-container {
            height: 580px;
            overflow-y: auto;
            
            &::-webkit-scrollbar {
                width: 6px;
            }
            
            &::-webkit-scrollbar-thumb {
                background-color: #ccc;
                border-radius: 3px;
            }
            
            &::-webkit-scrollbar-track {
                background-color: #f5f5f5;
            }
        }
    }

    .property-card {
        display: flex;
        gap: 16px;
        padding: 16px;
        cursor: pointer;
        transition: all 0.3s;
        border-bottom: 1px solid #f5f5f5;
        
        &:hover {
            background: #f8f9fa;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            transform: translateY(-2px);
        }
        
        .preview-image {
            width: 100px;
            height: 80px;
            border-radius: 4px;
            overflow: hidden;
            
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                transition: transform 0.3s;
                
                &:hover {
                    transform: scale(1.05);
                }
            }
        }
        
        .info {
            flex: 1;
            
            h4 {
                margin: 0 0 8px;
                font-size: 14px;
                color: #2F3B59;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            
            .price {
                color: #f56c6c;
                font-size: 18px;
                font-weight: 500;
                margin: 0 0 8px;
                
                span {
                    font-size: 12px;
                    color: #999;
                }
            }
            
            .meta {
                display: flex;
                gap: 12px;
                font-size: 12px;
                color: #666;
                margin-bottom: 10px;
                
                span {
                    display: flex;
                    align-items: center;
                    gap: 4px;
                    
                    .svg-icon {
                        width: 14px;
                        height: 14px;
                        color: #909399;
                    }
                }
            }
            
            .collect-btn {
                display: flex;
                align-items: center;
                gap: 5px;
                background: white;
                color: #f56c6c;
                border: 1px solid #f56c6c;
                border-radius: 4px;
                padding: 5px 10px;
                font-size: 12px;
                cursor: pointer;
                transition: all 0.2s;
                
                &:hover {
                    background: #fff3f3;
                    transform: translateY(-2px);
                }
                
                .svg-icon {
                    font-size: 12px;
                    color: #f56c6c;
                }
            }
        }
    }

    .map-controls {
        position: absolute;
        bottom: 20px;
        left: 20px;
        z-index: 100;

        .control-group {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            padding: 10px 8px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .control-btn {
            width: 36px;
            height: 36px;
            border: none;
            background: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            transition: all 0.3s;

            &:hover {
                background: #f0f5ff;
            }

            .svg-icon {
                width: 20px;
                height: 20px;
                color: #4A60A1;
                
                &:hover {
                    color: #2F3B59;
                }
            }
        }
    }

    // 添加房源标记样式
    :deep(.house-marker) {
        background: #4A60A1;
        color: #fff;
        padding: 6px 10px;
        border-radius: 4px;
        font-size: 12px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover, &.active {
            background: #2F3B59;
            transform: scale(1.05);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.3);
        }
        
        .price {
            white-space: nowrap;
            font-weight: bold;
        }
    }
    
    // 添加小区标记样式
    :deep(.community-marker) {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #4A60A1;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 14px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        border: 2px solid white;
        transition: all 0.3s ease;
        
        &:hover, &.active {
            background: #f56c6c;
            transform: scale(1.1);
        }
        
        .count {
            position: relative;
        }
    }
}
</style>